package com.example.myfirstapp;

import java.util.Calendar;
import java.lang.CharSequence;
import java.lang.Float;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.DatePicker;
import android.widget.ListPopupWindow;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.view.View.OnClickListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.content.ContentValues;
import android.content.Intent;

import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;

public class MainActivity extends Activity implements OnItemClickListener {
	EditText inputCategory;
	ListPopupWindow categoryWindow;
	EditText valueEditText;
	String [] categories;

	private String [] getCategories() {
		CategoriesHelper categoriesHelper = new CategoriesHelper(this);
		SQLiteDatabase database = categoriesHelper.getReadableDatabase();
		Cursor cursor = database.query(CategoriesHelper.TABLE_CATEGORIES,
				new String []
					{CategoriesHelper.COLUMN_MAIN, CategoriesHelper.COLUMN_SUB},
				null, null, null, null, null);
		String [] categories = new String[cursor.getCount()];
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			categories[cursor.getPosition()] =
				cursor.getString(0) + "/" + cursor.getString(1);
			cursor.moveToNext();
		}
		return categories;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		categories = getCategories();

		inputCategory = (EditText) findViewById(R.id.input_category);
		categoryWindow = new ListPopupWindow(MainActivity.this);
		categoryWindow.setAdapter(new ArrayAdapter(MainActivity.this,
					R.layout.list_item, categories));
		categoryWindow.setAnchorView(inputCategory);

		categoryWindow.setModal(true);
		categoryWindow.setOnItemClickListener(MainActivity.this);
		inputCategory.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				categoryWindow.show();
			}
		});

		valueEditText = (EditText) findViewById(R.id.input_value);
		valueEditText.addTextChangedListener(valueTextWatcher);
	}

	private final TextWatcher valueTextWatcher = new TextWatcher() {
		private String current = "";
		@Override
		public void onTextChanged(CharSequence s, int start,
				int before, int count) {
			String newValue = s.toString();
			if (newValue.equals(current)) {
				return;
			}
			newValue = newValue.replaceAll("\\D", "");
			int len = newValue.length();
			if (len > 2)
				newValue = newValue.substring(0, len-2) + "." +
					newValue.substring(len-2, len);
			current = newValue;
			valueEditText.setText(newValue);
			valueEditText.setSelection(newValue.length());
		}
		@Override
		public void beforeTextChanged(CharSequence s, int start,
				int count, int after) {};
		@Override
		public void afterTextChanged(Editable s) {};
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		inputCategory.setText(categories[position]);
		categoryWindow.dismiss();
	}

	public void storeValue(View view) {
		EditText categoryET = (EditText) findViewById(R.id.input_category);
		DatePicker datePicker = (DatePicker) findViewById(R.id.input_date);
		Calendar calendar = Calendar.getInstance();
		calendar.set(datePicker.getYear(), datePicker.getMonth(),
				datePicker.getDayOfMonth(), 0, 0, 0);

		OperationHelper operationHelper = new OperationHelper(this);
		SQLiteDatabase database = operationHelper.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(OperationHelper.COLUMN_VALUE,
				Float.valueOf(valueEditText.getText().toString()));
		values.put(OperationHelper.COLUMN_DATE, calendar.getTimeInMillis());
		values.put(OperationHelper.COLUMN_CATEGORIE,
				getCategorieId(categoryET.getText().toString()));

		database.insert(OperationHelper.TABLE_OPERATION, null, values);
	}

	private long getCategorieId(String categorie) {
		CategoriesHelper categoriesHelper = new CategoriesHelper(this);
		SQLiteDatabase database = categoriesHelper.getReadableDatabase();
		Cursor cursor = database.query(CategoriesHelper.TABLE_CATEGORIES,
				new String [] {CategoriesHelper.COLUMN_ID},
				CategoriesHelper.COLUMN_MAIN + "=\"" + categorie.split("/")[0] +
				"\" and " +
				CategoriesHelper.COLUMN_SUB + "=\"" + categorie.split("/")[1] +
				"\"",
				null, null, null, null);
		cursor.moveToFirst();
		return cursor.getLong(0);
	}

	public void listOperations(View view) {
		Intent intent = new Intent(this, ListActivity.class);
		startActivity(intent);
	}
}
